import os

from flask import request
from flask_restful import Resource

from database import Database

class CreateStack(Resource):
    def post(self):
        # Get the data from the request
        data = request.form

        # Extract the stack attributes from the request data
        stackId = data.get('stackId')
        categoryId = data.get('categoryId')
        imgUrl = data.get('imgUrl')
        title = data.get('title')
        description = data.get('description')
        author = data.get('author')
        status = 'Not Available'
        quantity = 0

        # Get the image file from the request

        # Save the image to the server
        image = request.files['image']
        image.save(os.path.join(os.getcwd(), 'assets/stacks/', stackId + '.jpg'))

        # Insert the new stack into the database
        db = Database()
        query = """INSERT INTO stack (stackId, categoryId, imgUrl, title, description, author, status, quantity)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
        db.execute_query(query, (stackId, categoryId, imgUrl, title, description, author, status, quantity))
        db.connection.commit()

        return {"message": "Stack created successfully", "stackId": stackId}, 201